//
//  EMSearchViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 15/1/7.
//  Copyright (c) 2015年 cczu. All rights reserved.
//

#import "EMSearchViewController.h"
#import "EMSearchBar.h"
#import "EMSearchReqBody.h"
#import "EMSearchRespBody.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "EMSortSegmentedControl.h"
#import "EMNewContentCell.h"
#import "EMGoodInfo3.h"
#import "UIImageView+WebCache.h"
#import "EMDetailInfoViewController.h"
#import "UserInfo.h"
#import "EMLoginViewController.h"
#import "EMShoppingCartViewController.h"
#import "MJRefresh.h"


@interface EMSearchViewController ()
{
    NSArray *titleArray;
    UITextField *tf0;
    EMSearchBar *search;
    AppDelegate *app;
    NSMutableArray *goodArray;
    NSArray *sortTitleArray;
    BOOL isIncreaseOfAmount;
    BOOL isIncreaseOfPrice;
    BOOL isIncreaseOfTime;
    UICollectionView *aCollectionView;
    EMSortSegmentedControl *seg;
    int page;
    NSString *aFlag;
}
@end

@implementation EMSearchViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.backgroundColor = RGB(242, 242, 242);
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    self.navigationController.navigationBarHidden = YES;
    sortTitleArray = [[NSArray alloc] init];
    isIncreaseOfAmount = NO;
    isIncreaseOfPrice = NO;
    isIncreaseOfTime = NO;
    aFlag = [[NSString alloc] init];
    page = 1;
    UIImage *imageQ = [UIImage imageNamed:@"logo_导航"];
    UIImageView *leftView = [[UIImageView alloc] initWithImage:[imageQ imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    leftView.frame = CGRectMake(10, 26, 110, 26);
    [self.view addSubview:leftView];;
    search = [[EMSearchBar alloc] initWithFrame:CGRectMake(130, 30, 140, 24)];
    search.placeholderText = @".";
    [self.view addSubview:search];
    
    for (UIView *tf in search.subviews) {
        if ([tf isKindOfClass:[UITextField class]]) {
            tf0 = (UITextField *)tf;
        }
    }
    tf0.delegate = self;
    tf0.returnKeyType = UIReturnKeySearch;
    
    [tf0 becomeFirstResponder];
    
    UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 140, 24)];
    cancelButton.frame = CGRectMake(280, 30, 30, 24);
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:RGB(101, 118, 32) forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    [cancelButton addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelButton];
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 63.5, 320, 0.5)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:lineView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    goodArray = [[NSMutableArray alloc] init];
    sortTitleArray = @[@"默认", @"按价格", @"按销量", @"按时间"];
    [self drawSeg];
    
    CGRect collectRect = [UIScreen mainScreen].bounds;
    collectRect.origin.y = 104;
    collectRect.size.height = [UIScreen mainScreen].bounds.size.height - 104;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    aCollectionView = [[UICollectionView alloc] initWithFrame:collectRect collectionViewLayout:flowLayout];
    [aCollectionView registerClass:[EMNewContentCell class] forCellWithReuseIdentifier:@"menuListCell"];
    aCollectionView.backgroundColor = RGB(242, 242, 242);
    aCollectionView.delegate = self;
    aCollectionView.dataSource = self;
    [aCollectionView addFooterWithTarget:self action:@selector(pullRefreshAction)];
    [self.view addSubview:aCollectionView];
    
    UIButton *cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cartBtn setImage:[UIImage imageNamed:@"button_进入购物车"] forState:UIControlStateNormal];
    [cartBtn setFrame:CGRectMake(20, [UIScreen mainScreen].bounds.size.height - 49 - 30, 55, 55)];
    [cartBtn addTarget:self action:@selector(enterToCart:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cartBtn];
}

- (void)cancelAction:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [tf0 resignFirstResponder];
    [self getListInfoWithFlag:@"1"];
    
    return YES;
}
- (void)pullRefreshAction
{
    [self getListInfoWithFlag:aFlag];
    [aCollectionView reloadData];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return goodArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    EMGoodInfo3 *goodInfo = [[EMGoodInfo3 alloc] initWithGoodInfo:goodArray[indexPath.row ]];
    
    static NSString *cellIdentifier = @"menuListCell";
    EMNewContentCell *cell = (EMNewContentCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    [cell.goodImageView sd_setImageWithURL:[NSURL URLWithString:goodInfo.m_imgUrl]];
    cell.goodNameLabel.text = goodInfo.m_name;
    cell.goodDescLabel.text = (NSNull *)goodInfo.m_goodDesc == [NSNull null] ? @"" : goodInfo.m_goodDesc;
    cell.priceLabel.text = [NSString stringWithFormat:@"¥%@", goodInfo.m_nowPrice];
    if ([goodInfo.m_mode isEqualToString:@"0"]) {
        cell.originPriceLabel.text = @"";
    } else {
        NSMutableAttributedString *oPrice = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"¥%@", goodInfo.m_originPrice]];
        [oPrice addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, goodInfo.m_originPrice.length+1)];
        cell.originPriceLabel.attributedText = oPrice;
    }
    cell.addToCart.tag = indexPath.row + 84000;
    [cell.addToCart addTarget:self action:@selector(addToCart:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
    
}
- (void)addToCart:(UIButton *)btn
{
    if ([UserInfo sharedUserInfo].m_isLogin) {
        EMGoodInfo3 *info = [[EMGoodInfo3 alloc] initWithGoodInfo:goodArray[btn.tag - 84000]];
        [app addToCartWithID:info.m_id];
    } else {
        [app showTip:@"请先登录"];
        EMLoginViewController *controller = [[EMLoginViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
    
}
- (void)enterToCart:(UIButton *)sender
{
    if ([UserInfo sharedUserInfo].m_isLogin) {
        EMShoppingCartViewController *controller = [[EMShoppingCartViewController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    } else {
        [app showTip:@"请先登录"];
        EMLoginViewController *controller = [[EMLoginViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    UIEdgeInsets top = {W(5), H(10), W(5), H(10)};
    return top;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(W(145), H(245));
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%zd %zd", indexPath.section ,indexPath.row);
    tf0.text = @"";
    search.placeholderText = @"";
    EMDetailInfoViewController *controller = [[EMDetailInfoViewController alloc] init];
    
    EMGoodInfo3 *goodInfo = [[EMGoodInfo3 alloc] initWithGoodInfo:goodArray[indexPath.row ]];
    controller.goodID = goodInfo.m_id;
    
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)drawSeg
{
    seg = [[EMSortSegmentedControl alloc] initWithFrame:CGRectMake(0, 84, [UIScreen mainScreen].bounds.size.width, 20)];
    [seg setTitleArray:sortTitleArray];
    [seg setActionBlock:^(NSUInteger index) {
        [goodArray removeAllObjects];
        [aCollectionView scrollsToTop];
        page = 1;
        switch (index) {
            case 0:
            {
                [self getListInfoWithFlag:@"7"];
                [aCollectionView reloadData];
                break;
            }
            case 1:
            {
                if (isIncreaseOfPrice == YES) {
                    [self getListInfoWithFlag:@"3"];
                } else {
                    [self getListInfoWithFlag:@"4"];
                }
                isIncreaseOfPrice = !isIncreaseOfPrice;
                [aCollectionView reloadData];
                break;
            }
            case 2:
            {
                if (isIncreaseOfAmount == YES) {
                    [self getListInfoWithFlag:@"1"];
                } else {
                    [self getListInfoWithFlag:@"2"];
                }
                isIncreaseOfAmount = !isIncreaseOfAmount;
                [aCollectionView reloadData];
                break;
            }
            case 3:
            {
                if (isIncreaseOfTime == YES) {
                    [self getListInfoWithFlag:@"5"];
                } else {
                    [self getListInfoWithFlag:@"6"];
                }
                isIncreaseOfTime = !isIncreaseOfTime;
                [aCollectionView reloadData];
                break;
            }
            default:
                break;
        }
    }];
    
}
- (void)getListInfoWithFlag:(NSString *)flag
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    EMSearchReqBody *reqBody = [[EMSearchReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"GOODS-SEARCH-LIST";
    reqBody.ID = tf0.text;
    reqBody.GETTIMES = [NSString stringWithFormat:@"%d",page];
    reqBody.FLAG = flag;
    aFlag = flag;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMSearchRespBody *respBody = [EMSearchRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            [aCollectionView footerEndRefreshing];
            if (respBody.GOODINFO.count != 0) {
                page ++;
            }
            
            
            for (int i = 0; i < respBody.GOODINFO.count; i ++) {
                [goodArray addObject:respBody.GOODINFO[i]];
            }

            [self.view addSubview:seg];
            [aCollectionView reloadData];
            
        } else {
            [aCollectionView footerEndRefreshing];
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    
}

@end
